package io.gitee.yxsnake.framework.retrofit.interceptor;

import com.github.lianjiatech.retrofit.spring.boot.interceptor.GlobalInterceptor;
import io.gitee.yxsnake.framework.core.constant.TraceCons;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.MDC;

import java.io.IOException;

/**
 * @author snake
 * @description
 * @since 2024/11/20 10:53
 */
public class RetrofitTraceIdInterceptor implements GlobalInterceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        String traceId = MDC.get(TraceCons.TRACE_ID);
        String clientIp = MDC.get(TraceCons.CLIENT_IP);
        Request request = null;
        if (traceId != null) {
            //添加请求体
            request = chain.request().newBuilder()
                    .addHeader(TraceCons.TRACE_ID, traceId)
                    .addHeader(TraceCons.CLIENT_IP, clientIp)
                    .build();
        }else{
            request = chain.request();
        }

        return chain.proceed(request);
    }
}

